using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using YourNamespace.Data;
using YourNamespace.Models.Requests;

namespace YourNamespace.Services
{
    public class ProductionPlanningService : IProductionPlanningService
    {
        private readonly ApplicationDbContext _context;

        public ProductionPlanningService(ApplicationDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 批量处理生产计划排程
        /// </summary>
        public async Task<BatchScheduleResult> BatchScheduleAsync(BatchScheduleRequest request)
        {
            var result = new BatchScheduleResult
            {
                Success = true,
                Results = new List<ScheduleItemResult>()
            };

            try
            {
                foreach (var planId in request.ProductionPlanningIds)
                {
                    var itemResult = new ScheduleItemResult
                    {
                        ProductionPlanningId = planId
                    };

                    try
                    {
                        // 1. 获取生产计划
                        var plan = await _context.ProductionPlans
                            .FirstOrDefaultAsync(p => p.ProductionPlanningId == planId);

                        if (plan == null)
                        {
                            itemResult.Success = false;
                            itemResult.ErrorMessage = "未找到对应的生产计划";
                            continue;
                        }

                        // 2. 验证工人和机床的可用性
                        if (!await ValidateWorkersAndMachines(request.SelectedWorkers, request.SelectedMachines, 
                            request.PlannedStartDate, request.PlannedEndDate))
                        {
                            itemResult.Success = false;
                            itemResult.ErrorMessage = "所选工人或机床在指定时间段内不可用";
                            continue;
                        }

                        // 3. 创建排程记录
                        var schedule = new ProductionSchedule
                        {
                            ProductionPlanningId = planId,
                            PlannedStartDate = request.PlannedStartDate,
                            PlannedEndDate = request.PlannedEndDate,
                            Status = "已排程",
                            CreateDate = DateTime.Now
                        };

                        _context.ProductionSchedules.Add(schedule);

                        // 4. 创建工人排程关联
                        foreach (var worker in request.SelectedWorkers)
                        {
                            var workerSchedule = new WorkerSchedule
                            {
                                ScheduleId = schedule.ScheduleId,
                                WorkingHoursId = worker.WorkingHoursId,
                                WorkerCode = worker.WorkerCode,
                                WorkerName = worker.WorkerName,
                                Department = worker.Department,
                                Team = worker.Team
                            };
                            _context.WorkerSchedules.Add(workerSchedule);
                        }

                        // 5. 创建机床排程关联
                        foreach (var machine in request.SelectedMachines)
                        {
                            var machineSchedule = new MachineSchedule
                            {
                                ScheduleId = schedule.ScheduleId,
                                DeviceId = machine.DeviceId,
                                DeviceCode = machine.DeviceCode,
                                DeviceName = machine.DeviceName,
                                DeviceState = machine.DeviceState
                            };
                            _context.MachineSchedules.Add(machineSchedule);
                        }

                        // 6. 更新生产计划状态
                        plan.Status = "已排程";
                        plan.UpdateDate = DateTime.Now;

                        itemResult.Success = true;
                    }
                    catch (Exception ex)
                    {
                        itemResult.Success = false;
                        itemResult.ErrorMessage = ex.Message;
                    }

                    result.Results.Add(itemResult);
                }

                // 保存所有更改
                await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Message = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 验证工人和机床的可用性
        /// </summary>
        private async Task<bool> ValidateWorkersAndMachines(
            List<WorkerInfo> workers,
            List<MachineInfo> machines,
            DateTime startDate,
            DateTime endDate)
        {
            // 验证工人可用性
            foreach (var worker in workers)
            {
                var hasConflict = await _context.WorkerSchedules
                    .AnyAsync(ws => ws.WorkingHoursId == worker.WorkingHoursId &&
                        ((ws.PlannedStartDate <= startDate && ws.PlannedEndDate >= startDate) ||
                         (ws.PlannedStartDate <= endDate && ws.PlannedEndDate >= endDate)));

                if (hasConflict)
                {
                    return false;
                }
            }

            // 验证机床可用性
            foreach (var machine in machines)
            {
                var hasConflict = await _context.MachineSchedules
                    .AnyAsync(ms => ms.DeviceId == machine.DeviceId &&
                        ((ms.PlannedStartDate <= startDate && ms.PlannedEndDate >= startDate) ||
                         (ms.PlannedStartDate <= endDate && ms.PlannedEndDate >= endDate)));

                if (hasConflict)
                {
                    return false;
                }
            }

            return true;
        }
    }
} 